package algorithm.swordoff;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * 从上到下打印二叉树II
 * BFS使用队列
 *
 * 注意不能在for循环里面调整add left和right的顺序因为可能层中节点先后顺序没关系比如
 *
 *      1
 *     / \
 *    2  3
 *   /    \
 *  4     5
 *
 */


public class SQ32_3 {

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ans = new LinkedList<>();
        if (root == null) return ans;
        Queue<TreeNode> queue = new LinkedList<TreeNode>() {{add(root);}};

        while (!queue.isEmpty()) {
            List<Integer> tmp = new LinkedList<>();
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
                tmp.add(poll.val);
                if (poll.left != null) queue.add(poll.left);
                if (poll.right != null) queue.add(poll.right);

            }
            if ((ans.size()&1) == 1) Collections.reverse(tmp);
            ans.add(tmp);
        }

        return ans;
    }


}
